package com.kafka.consumer;

import java.io.IOException;
import java.util.Collections;
import java.util.Properties;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;


public class Consumer {

	public static void main(String[] args) throws IOException {

		// 1.实例化consumer对象
		Properties properties = new Properties();

		properties.load(Consumer.class.getClassLoader().getResourceAsStream("consumer.properties"));

		KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);

		// 2.用这个对象接收消息
		// 订阅主题
		consumer.subscribe(Collections.singleton("hello2"));

		while(true) {

			// 拉取数据
			ConsumerRecords<String, String> poll = consumer.poll(2000);

			// 如果没有数据可以消费了就等待1ms
			if(poll.count() == 0) {

				Thread.holdsLock(100);

			}

			// 遍历数据
			for (ConsumerRecord<String, String> record : poll) {

				System.out.println(record);

			}

			// 每次消费完数据将数据手动提交
			consumer.commitSync();

		}


		// 3.关闭对象
//		consumer.close();

	}

}
